package com.ruoyi.common.utils.rtf;

import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.rtf.RTFEditorKit;
import java.io.ByteArrayInputStream;
import java.util.Enumeration;

public class RtfToZh {


    public static String parseRtf(String rtfJieshi) {
        String result = "";
        try {
            //替换特殊样式符号
            rtfJieshi = transSpecialCharactersToGBK(rtfJieshi);
            //替换特殊字节
            rtfJieshi = transSpecialISO(rtfJieshi);
            byte[] b = rtfJieshi .getBytes();
            DefaultStyledDocument styledDoc = new DefaultStyledDocument();
            new RTFEditorKit().read(new ByteArrayInputStream(b), styledDoc, 0);
            byte[] data = styledDoc.getText(0,styledDoc.getLength()).getBytes("ISO8859_1");
            //data = inverseSpecial(data);
            //注意这边加上GBK
            result = new String(data,"GBK");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 将Special Characters转换成gbk编码
     * @return
     */
    private static String transSpecialCharactersToGBK(String rtfStr) {
        if (rtfStr != null && rtfStr.length() > 0) {
            for(Enumeration e = TransKey.textKeywords.keys(); e.hasMoreElements();){
                String thisName=e.nextElement().toString();
                String thisValue= TransKey.textKeywords.get(thisName);
                rtfStr = rtfStr.replaceAll(thisName, thisValue);
            }
            return rtfStr;
        } else {
            return "";
        }
    }

    /**
     * 将ISO8859-1没有定义的字节进行转义
     * @return
     */
    private static String transSpecialISO(String rtfStr) {
        return ISO8859ISpecialByte.conversionStr(rtfStr);
    }

    /**
     * 将ISO8859-1没有定义的字节进行反转义
     * @return
     */
    private static byte[] inverseSpecial(byte[] data) {
        return ISO8859ISpecialByte.inverseStr(data);
    }


}
